package com.vhall.component.service.data.impl;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.date.StopWatch;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vhall.component.dao.data.AccountForDataMapper;
import com.vhall.component.dao.livecolumn.LiveColumnMapper;
import com.vhall.component.dao.room.RoomMapper;
import com.vhall.component.dao.tag.AdvertisingMapper;
import com.vhall.component.entity.account.enums.GuoXinStaffEnums;
import com.vhall.component.entity.data.vo.*;
import com.vhall.component.entity.dictionary.enums.GuoXinAccountTypeEnum;
import com.vhall.component.entity.dictionary.enums.PlacementLocationEnum;
import com.vhall.component.entity.livecolumn.entity.LiveColumnEntity;
import com.vhall.component.entity.page.vo.PageVO;
import com.vhall.component.entity.room.entity.AnchorRoomRelationEntity;
import com.vhall.component.entity.room.entity.RoomsEntity;
import com.vhall.component.entity.room.enums.*;
import com.vhall.component.entity.tag.AdvertisingEntity;
import com.vhall.component.entity.tag.enums.AdverShelvesEnum;
import com.vhall.component.entity.tag.vo.AdvertisingListRspVO;
import com.vhall.component.framework.common.utils.CollectionUtils;
import com.vhall.component.plugin.common.constant.RedisKey;
import com.vhall.component.plugin.common.enums.DeleteStatusEnum;
import com.vhall.component.plugin.common.support.Token;
import com.vhall.component.plugin.common.utils.BeanCopyUtil;
import com.vhall.component.plugin.core.service.PaasService;
import com.vhall.component.service.data.AggregationPageService;
import com.vhall.component.service.guosen.ExternalLiveStatsService;
import com.vhall.component.service.guosen.GuosenIfcPeHoldService;
import com.vhall.component.service.room.RoomWhitePhoneRelationService;
import com.vhall.component.service.room.impl.RoomBaseService;
import com.vhall.component.service.room.utils.RoomUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.MessageFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import static com.vhall.component.plugin.common.constant.RedisKey.*;

/**
 * @author shimingming
 * @since 2023/5/29 17:29
 */
@Slf4j
@Service
public class AggregationPageServiceImpl extends RoomBaseService implements AggregationPageService {

    @Resource
    private AdvertisingMapper advertisingMapper;

    @Autowired
    public RoomMapper roomMapper;

    @Autowired
    public PaasService paasService;

    /**
     * 是否开启房间审核
     * 1为开启
     * 0为关闭房间审核
     */
    @Value("${project.room.audit:0}")
    public Integer roomAuditWitch;

    @Autowired
    private AccountForDataMapper accountForDataMapper;

    @Resource
    private LiveColumnMapper liveColumnMapper;
    @Resource
    private RoomWhitePhoneRelationService phoneRelationService;
    @Resource
    private GuosenIfcPeHoldService guosenIfcPeHoldService;
    @Resource
    private ExternalLiveStatsService externalLiveStatsService;

    @Value("${guoxin.column.default_name:''}")
    private String defaultName;

    /**
     * 过期时间单位是秒
     */
    private final Integer timeout = 2;


    @Override
    public List<AdvertisingListRspVO> getBannerList() {

        String key = CACHE_GETBANNERLIST;
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return JSON.parseArray(o.toString(), AdvertisingListRspVO.class);
        }

        LambdaQueryWrapper<AdvertisingEntity> wrapperReser = Wrappers.lambdaQuery();
        wrapperReser.eq(AdvertisingEntity::getColumnId, 0);
        wrapperReser.eq(AdvertisingEntity::getIsDelete, DeleteStatusEnum.NO_DELETE.getStatus());
        wrapperReser.eq(AdvertisingEntity::getIsShelves, AdverShelvesEnum.LISTED.getValue());
        wrapperReser.eq(AdvertisingEntity::getPlacementLocation, PlacementLocationEnum.ROTATION_CHART.getValue());
        wrapperReser.orderByAsc(AdvertisingEntity::getSort);
        wrapperReser.last("limit 10");
        List<AdvertisingEntity> advertisingEntities = advertisingMapper.selectList(wrapperReser);
        List<AdvertisingListRspVO> rspVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(advertisingEntities)) {
            rspVOS = BeanCopyUtil.batchCopy(advertisingEntities, AdvertisingListRspVO::new);
            List<Integer> ilIdList = rspVOS.stream().map(AdvertisingListRspVO::getIlId).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ilIdList)) {
                Map<Integer, RoomsEntity> integerMap = new HashMap<>();
                LambdaQueryWrapper<RoomsEntity> roomWrapper = Wrappers.lambdaQuery();
                roomWrapper.in(RoomsEntity::getIlId, ilIdList);
                List<RoomsEntity> roomsEntities = roomMapper.selectList(roomWrapper);
                if (CollectionUtils.isNotEmpty(roomsEntities)) {
                    integerMap = roomsEntities.stream().collect(Collectors.toMap(RoomsEntity::getIlId, e -> e));
                }
                for (AdvertisingListRspVO rspVO : rspVOS) {
                    if (rspVO.getIlId() != null) {
                        RoomsEntity roomsEntity = integerMap.get(rspVO.getIlId());
                        rspVO.setLiveType(roomsEntity != null ? roomsEntity.getLiveType() : null);
                        rspVO.setStatus(roomsEntity != null ? roomInnerService.getShowRoomStatus(roomsEntity) : null);
                    }
                }
            }


            redisTemplate.opsForValue().set(key, JSON.toJSONString(rspVOS), timeout, TimeUnit.SECONDS);

        }
        return rspVOS;
    }

    public Token getTokenFromVO(String tokenStr) {
        if (StringUtils.isNotBlank(tokenStr)) {
            Object tokenObject = redisTemplate.opsForValue().get(RedisKey.AUTH_TOKEN + tokenStr);
            if (tokenObject != null) {
                String tokenText = JSON.parse(tokenObject.toString()).toString();
                Token token = JSON.parseObject(tokenText, Token.class);
                return token;
            }
        }
        return null;
    }


    @Override
    public List<LiveScheduleDetailRspVO> liveSchedule(LiveScheduleReqVO reqVO) {
        Integer guoXinAccountType = GuoXinAccountTypeEnum.TOURIST.getValue();
        String orgCode = "";
//        客户号
        String custId = "";
//        资金号
        String fundId = "";
//        手机号
        String phone = "";
        Integer staff = 0;
        if (StringUtils.isNotBlank(reqVO.getToken())) {
            Token token = getTokenFromVO(reqVO.getToken());
            custId = token.getCustId();
            fundId = token.getFundId();
            phone = token.getPhone();
            guoXinAccountType = token.getGuoXinAccountType();
            orgCode = token.getOrgCode();
            staff = token.getStaff();
        }

        String key = MessageFormat.format("{0}:{1}:{2}:{3}", CACHE_LIVESCHEDULE, guoXinAccountType, orgCode,staff);
        boolean notStaff = Objects.equals(staff, GuoXinStaffEnums.NO_STAFF.getValue());
        if (notStaff && isSpecialAccount(custId, fundId, phone)) {
            key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}"
                    , CACHE_LIVESCHEDULE, guoXinAccountType, orgCode
                    , custId, fundId, phone);
        }
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return JSON.parseArray(o.toString(), LiveScheduleDetailRspVO.class);
        }

        List<LiveColumnEntity> liveColumnEntities = liveColumnMapper.selectListForColumnList(guoXinAccountType, orgCode);
        if (CollectionUtils.isEmpty(liveColumnEntities)) {
            return new ArrayList<>();
        }


        LambdaQueryWrapper<RoomsEntity> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(RoomsEntity::getAuditStatus, RoomAuditStatusEnum.APPROVED.getAuditStatus());
        String finalOrgCode = orgCode;
        wrapper.and(w->w.in(CollectionUtils.isNotEmpty(liveColumnEntities)
                , RoomsEntity::getColumnId
                , liveColumnEntities.stream().map(LiveColumnEntity::getId).collect(Collectors.toList()))
                .or()
                .apply(StrUtil.isNotBlank(finalOrgCode)," ( rooms.column_id=0 and rooms.org_code='"+ finalOrgCode +"') ")
                .apply(StrUtil.isBlank(finalOrgCode)," rooms.column_id=0 ")
        );

        wrapper.in(RoomsEntity::getStatus, Arrays.asList(RoomStatusEnum.LIVE_BROADCAST.getStatus(), RoomStatusEnum.TO_BE_BROADCAST.getStatus()));
        wrapper.eq(RoomsEntity::getLiveRormal, LiveRormalEnum.OFFICIAL_LIVE.getValue());
        wrapper.eq(RoomsEntity::getLiveInlet, LiveInletEnum.SHOW_IN_LIVE.getValue());
        wrapper.apply(notStaff," (\n" +
                "(rooms.limit_user_scope=0)\n" +
                "or(rooms.limit_user_scope=1\n" +
                "and exists( select rpr.id from room_prod_relation rpr\n" +
                "where rpr.type=1 and rpr.il_id=rooms.il_id\n" +
                "and exists(select giph.ofcode from guosen_ifc_pe_hold giph\n" +
                "where giph.ofcode=rpr.ofcode and (\n" +
                "giph.custid={0}\n" +
                "or\n" +
                "giph.fundId={1}\n" +
                ") ) ) )\n" +
                "or(rooms.limit_user_scope=2\n" +
                "and exists(select rwpr.id from room_white_phone_relation rwpr where rwpr.il_id=rooms.il_id\n" +
                "and rwpr.phone={2}\n" +
                "))\n" +
                ") ",custId,fundId,phone);
        wrapper.last("ORDER BY FIELD(`status`,1,0) , start_time asc,il_id asc  ");
        List<RoomsEntity> roomsEntityList = roomMapper.selectList(wrapper);
        List<LiveScheduleDetailRspVO> rspVOS = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(roomsEntityList)) {

            // 过滤掉还是待直播，且到期没有直播的房间
            roomsEntityList = roomsEntityList.stream().filter(this::notStart).collect(Collectors.toList());
            if (CollectionUtils.isEmpty(roomsEntityList)) {
                return new ArrayList<>();
            }
//            对于直播的状态进行额外处理设置
            roomsEntityList = roomsEntityList.stream().map(data->{
                data.setStatus(roomInnerService.getShowRoomStatus(data));
                return data;
            }).collect(Collectors.toList());
            rspVOS = BeanCopyUtil.batchCopy(roomsEntityList, LiveScheduleDetailRspVO::new);
            // 获取栏目信息
            Map<Integer, String> columnMap = getColumnStringMap(roomsEntityList);
            // 获取主播名称
            Map<Integer, AnchorRoomRelationEntity> userNameMap = getUserName(roomsEntityList);

            for (LiveScheduleDetailRspVO vo : rspVOS) {
                vo.setAnchorName(userNameMap.isEmpty() || userNameMap.get(vo.getIlId()) == null ? "" : userNameMap.get(vo.getIlId()).getUserName());
                vo.setColumnName(columnMap.isEmpty() || vo.getColumnId() == null || vo.getColumnId() == 0 ? defaultName : columnMap.get(vo.getColumnId()));
                vo.setLiveContentTypeName(LiveContentTypeEnum.getDescription(vo.getLiveContentType()));
            }
            redisTemplate.opsForValue().set(key, JSON.toJSONString(rspVOS), timeout, TimeUnit.SECONDS);
        }

        return rspVOS;
    }

    private boolean notStart(RoomsEntity e) {
        LocalDateTime now = LocalDateTimeUtil.now();
        LocalDateTime startTime = e.getStartTime();
        Integer status = roomInnerService.getShowRoomStatus(e);
        if (status.equals(RoomStatusEnum.TO_BE_BROADCAST.getStatus()) && startTime.isBefore(now)) {
            return false;
        }
        return true;
    }

    @Override
    public List<ColumnListRspVO> getColumnList(ColumnListReqVO reqVO) {

        Integer guoXinAccountType = GuoXinAccountTypeEnum.TOURIST.getValue();
        String orgCode = "";
        String userCode = null;
        if (StringUtils.isNotBlank(reqVO.getToken())) {
            Token token = getTokenFromVO(reqVO.getToken());
            guoXinAccountType = token.getGuoXinAccountType();
            orgCode = token.getOrgCode();
            userCode = token.getThirdPartyUserId();
        }

        String key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}", CACHE_GETCOLUMNLIST, reqVO.getKeyword(), guoXinAccountType, orgCode, userCode == null ? "" : userCode);
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return JSON.parseArray(o.toString(), ColumnListRspVO.class);
        }

        List<LiveColumnEntity> liveColumnEntities = new ArrayList<>();
        if ("1".equals(reqVO.getKeyword())) {
            liveColumnEntities = liveColumnMapper.selectListForColumnList(guoXinAccountType, orgCode);
        } else {
            if (userCode != null) {
                // 关注
                liveColumnEntities = liveColumnMapper.selectListForAttentionColumnList(userCode);
            }
        }
        List<ColumnListRspVO> result = new ArrayList<>();
        if (CollectionUtils.isNotEmpty(liveColumnEntities)) {
            for (LiveColumnEntity entity : liveColumnEntities) {
                result.add(ColumnListRspVO.builder().columnId(entity.getId()).columnName(entity.getName()).columnImage(entity.getColumnImageUrl()).build());
            }
            redisTemplate.opsForValue().set(key, JSON.toJSONString(result), timeout, TimeUnit.SECONDS);
        }

        return result;
    }


    @Override
    public PageVO<SelectedVideoRspVO> selectedVideoList(SelectedVideoReqVO reqVO) {
        int currPage = reqVO.getPage() == null ? 1 : reqVO.getPage();
        int pageSize = reqVO.getPageSize() == null ? 20 : reqVO.getPageSize();

        Integer guoXinAccountType = GuoXinAccountTypeEnum.TOURIST.getValue();
        String orgCode = "";
//        客户号
        String custId = "";
//        资金号
        String fundId = "";
//        手机号
        String phone = "";
//        是否为员工: 0：非员工 1：员工
        Integer staff = 0;
        if (StringUtils.isNotBlank(reqVO.getToken())) {
            Token token = getTokenFromVO(reqVO.getToken());
            fundId = token.getFundId();
            custId = token.getCustId();
            phone = token.getPhone();
            guoXinAccountType = token.getGuoXinAccountType();
            orgCode = token.getOrgCode();
            staff = token.getStaff();
        }

        String key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}:{6}"
                , CACHE_SELECTEDVIDEOLIST, currPage, pageSize
                , reqVO.getColumnId(), guoXinAccountType, orgCode, staff
        );


        String key2 = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}:{6}"
                , CACHE_SELECTEDVIDEOLIST_COUNT, currPage, pageSize
                , reqVO.getColumnId(), guoXinAccountType, orgCode, staff);
//        特殊观众单独进行缓存
        if (Objects.equals(GuoXinStaffEnums.NO_STAFF.getValue(),staff) && isSpecialAccount(custId, fundId, phone)) {
            key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}:{8}"
                    , CACHE_SELECTEDVIDEOLIST, currPage, pageSize
                    , reqVO.getColumnId(), guoXinAccountType, orgCode
                    , custId, fundId, phone
            );

            key2 = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}:{6}:{7}:{8}"
                    , CACHE_SELECTEDVIDEOLIST_COUNT, currPage, pageSize
                    , reqVO.getColumnId(), guoXinAccountType, orgCode
                    , custId, fundId, phone);
        }

        Object o = redisTemplate.opsForValue().get(key);
        Object o2 = redisTemplate.opsForValue().get(key2);

        List<SelectedVideoRspVO> rooms = new ArrayList<>();
        List<RoomsEntity> roomsEntities = new ArrayList<>();
        int total = 0;
        if (o != null && o2 != null) {
            rooms = JSON.parseArray(o.toString(), SelectedVideoRspVO.class);
            total = Integer.parseInt(o2.toString());
        } else {
            Page<RoomsEntity> page = new Page<>(currPage, pageSize);
            IPage<RoomsEntity> entityIpage;
            if (reqVO.getColumnId() == null || reqVO.getColumnId().equals(0)) {
                entityIpage = roomMapper.selectedVideoList(page, reqVO, guoXinAccountType, orgCode, phone, custId, fundId, staff);
            } else {
                entityIpage = roomMapper.selectedVideoListForColumn(page, reqVO, phone, custId, fundId, staff);
            }


            if (entityIpage != null && entityIpage.getRecords() != null && CollectionUtils.isNotEmpty(entityIpage.getRecords())) {
                roomsEntities = entityIpage.getRecords();
                total = Math.toIntExact(entityIpage.getTotal());
            }
            if (CollectionUtils.isNotEmpty(roomsEntities)) {
                // 获取栏目信息
                Map<Integer, String> columnMap = getColumnStringMap(roomsEntities);
                // 获取主播名称
                Map<Integer, AnchorRoomRelationEntity> userNameMap = getUserName(roomsEntities);

                Map<Integer, Long> virtualPV = roomInnerService.getVirtualPV(roomsEntities.stream().map(RoomsEntity::getIlId).collect(Collectors.toList()));
                for (RoomsEntity record : roomsEntities) {
                    rooms.add(convertToRoomsEntityVO(record, columnMap, userNameMap, virtualPV));
                }


                redisTemplate.opsForValue().set(key, JSON.toJSONString(rooms), timeout, TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(key2, total, timeout, TimeUnit.SECONDS);
            }

        }


        return new PageVO<>(reqVO.getPage(), reqVO.getPageSize(), total, rooms);

    }

    /**
     * 当前登录用户是否为特殊客户
     * - 是手机号白名单特殊客户
     * - 是购买过指定私募产品客户
     * @param custId 客户号
     * @param fundId 资金账号
     * @param phone 手机号
     * @return
     */
    private boolean isSpecialAccount(String custId, String fundId, String phone) {
        if(StrUtil.isBlank(custId + fundId + phone)){
            return false;
        }
        StopWatch stopWatch = new StopWatch();
        stopWatch.start("获取手机号");
        if (StrUtil.isNotBlank(phone)) {
            Set<String> phoneSet = phoneRelationService.getCacheAllWhitePhoneList();
            if(phoneSet.contains(phone)){
                return true;
            }
        }
        stopWatch.stop();
        stopWatch.start("获取资金账号");
        Set<String> fundSet = guosenIfcPeHoldService.getCacheAllCustIDAndFundIDList();
        stopWatch.stop();
        log.info("获取信息的执行时间:{}ms,{}",stopWatch.getTotalTimeMillis(),stopWatch.prettyPrint());
        return fundSet.contains(custId)||fundSet.contains(fundId);
    }

    /**
     * 数据类型转换
     *
     * @param room
     * @param columnMap
     * @param userNameMap
     * @param virtualPV
     * @return
     */
    private SelectedVideoRspVO convertToRoomsEntityVO(RoomsEntity room, Map<Integer, String> columnMap, Map<Integer, AnchorRoomRelationEntity> userNameMap, Map<Integer, Long> virtualPV) {
        SelectedVideoRspVO vo = new SelectedVideoRspVO();
        // 拷贝实体
        BeanUtils.copyProperties(room, vo);
        vo.setName(room.getSubject());
        vo.setImage(room.getCoverImage());
        //查询 直播时长
        vo.setLiveTime(findLiveTime(room));

//        获取直播对外显示的直播状态
        Integer showRoomStatus = roomInnerService.getShowRoomStatus(room);
        String statusStr = RoomUtils.getRoomStatusStr(room.getAuditStatus(), showRoomStatus, roomAuditWitch);
        vo.setStatus(showRoomStatus);
        vo.setStatusStr(statusStr);
        int pvCount = getPvCountFromStatics(room);
        Integer ilId = room.getIlId();
        int pv = !virtualPV.isEmpty() && virtualPV.get(ilId) != null ? Math.toIntExact(virtualPV.get(ilId)) + pvCount : pvCount;
        Integer totalNumberOfViews = Optional.ofNullable(room.getTotalNumberOfViews()).orElse(0);
        int liveExternalChannelViewCount = externalLiveStatsService.getCacheLiveExternalChannelViewCount(ilId);
        pv += totalNumberOfViews;
//        增加外部观看次数相关逻辑
        pv += liveExternalChannelViewCount;
        vo.setPv(pv);
        vo.setColumnName(columnMap.isEmpty() || room.getColumnId() == null || room.getColumnId() == 0 ? defaultName : columnMap.get(room.getColumnId()));
        vo.setUserName(userNameMap.isEmpty() || userNameMap.get(room.getIlId()) == null ? "" : userNameMap.get(room.getIlId()).getUserName());
        vo.setOrgName(userNameMap.isEmpty() || userNameMap.get(room.getIlId()) == null ? "" : userNameMap.get(room.getIlId()).getOrgName());
        vo.setOrgCode(userNameMap.isEmpty() || userNameMap.get(room.getIlId()) == null ? "" : userNameMap.get(room.getIlId()).getOrgCode());
        vo.setLiveContentTypeName(LiveContentTypeEnum.getDescription(vo.getLiveContentType()));
        return vo;
    }

    private int getPvCountFromStatics(RoomsEntity room) {
        UserParamVO reqVO = new UserParamVO();
        Integer ilId = room.getIlId();
        reqVO.setIlId(ilId);

        String key = MessageFormat.format("{0}:{1}", CACHE_SELECTEDVIDEOLIST_GETPVCOUNTFROMSTATICS, JSON.toJSONString(reqVO));
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return Integer.parseInt(o.toString());
        }

        UserBasicStatisticsRspVO ubsrv = accountForDataMapper.getBasicStatisticsInfo(reqVO);
        int pvCount = (ubsrv.getPvCount() != null && ubsrv.getPvCount() > 0) ? ubsrv.getPvCount() : 0;

        UserBasicStatisticsRspVO ubsrvVod = accountForDataMapper.getVodBasicStatisticsInfo(reqVO);
        pvCount += (ubsrvVod.getPvCount() != null && ubsrvVod.getPvCount() > 0) ? ubsrvVod.getPvCount() : 0;
        redisTemplate.opsForValue().set(key, pvCount, timeout, TimeUnit.SECONDS);
        return pvCount;
    }


    @Override
    public List<SelectedVideoRspVO> searchVideoList(SearchVideoReqVO reqVO) {


        Integer guoXinAccountType = GuoXinAccountTypeEnum.TOURIST.getValue();
        String orgCode = "";
        String custId = "";
        String fundId = "";
        String phone = "";
        Integer staff = 0;
        if (StringUtils.isNotBlank(reqVO.getToken())) {
            Token token = getTokenFromVO(reqVO.getToken());
            guoXinAccountType = token.getGuoXinAccountType();
            orgCode = token.getOrgCode();
            custId = token.getCustId();
            fundId = token.getFundId();
            phone = token.getPhone();
            staff = token.getStaff();
        }

        String key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}", CACHE_SEARCHVIDEOLIST, reqVO.getKeyword(), guoXinAccountType, orgCode,staff);
        if (Objects.equals(staff,GuoXinStaffEnums.NO_STAFF.getValue()) && isSpecialAccount(custId, fundId, phone)) {
            key = MessageFormat.format("{0}:{1}:{2}:{3}:{4}:{5}:{6}"
                    , CACHE_SEARCHVIDEOLIST, reqVO.getKeyword(), guoXinAccountType, orgCode
                    , custId, fundId, phone
            );
        }
        Object o = redisTemplate.opsForValue().get(key);
        if (o != null) {
            return JSON.parseArray(o.toString(), SelectedVideoRspVO.class);
        }

        List<RoomsEntity> roomsEntityList = roomMapper.searchVideoList(reqVO, guoXinAccountType, orgCode, phone, custId, fundId,staff);
        List<SelectedVideoRspVO> rooms = new ArrayList<>();

        if (CollectionUtils.isNotEmpty(roomsEntityList)) {

            // 获取栏目信息
            Map<Integer, String> columnMap = getColumnStringMap(roomsEntityList);
            // 获取主播名称
            Map<Integer, AnchorRoomRelationEntity> userNameMap = getUserName(roomsEntityList);

            Map<Integer, Long> virtualPV = roomInnerService.getVirtualPV(roomsEntityList.stream().map(RoomsEntity::getIlId).collect(Collectors.toList()));
            for (RoomsEntity record : roomsEntityList) {
                rooms.add(convertToRoomsEntityVO(record, columnMap, userNameMap, virtualPV));
            }
            redisTemplate.opsForValue().set(key, JSON.toJSONString(rooms), timeout, TimeUnit.SECONDS);

        }

        return rooms;
    }

}
